package com.wd.mine.work

import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.graphics.Color
import android.os.Build
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.work.Constraints
import androidx.work.CoroutineWorker
import androidx.work.Data
import androidx.work.ForegroundInfo
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.WorkerParameters
import com.wd.mine.R
import java.util.UUID

class DownloadWorker(appContext: Context, params: WorkerParameters) :
    CoroutineWorker(appContext, params) {
    override suspend fun doWork(): Result {
        val inputUrl = inputData.getString(KEY_INPUT_URL)
            ?: return Result.failure()
        val outputUrl = inputData.getString(KEY_OUT_PUT_URL)
            ?: return Result.failure()
        val filename = inputData.getString(KEY_OUTPUT_FILE_NAME)
            ?: return Result.failure()
        val progress = "Starting Download"
        setForeground(createForegroundInfo(progress))
        download(inputUrl, outputUrl, filename)
        return Result.success()
    }
    private suspend fun download(downloadUrl: String, outputFile: String, fileName: String) {
        KCHttpV2.download(downloadUrl, "$outputFile$fileName", onProcess = { _, _, process ->
            setForeground(createForegroundInfo("${(process * 100).toInt()}%"))
            setProgress(Data.Builder().let {
                it.putInt("progress", (process * 100).toInt())
                it.build()
            })
        }, onSuccess = {
            setForeground(createForegroundInfo("download ok"))
        },onError = {
            it.printStackTrace()
        })
    }
    private fun createForegroundInfo(progress: String): ForegroundInfo {
        val intent = WorkManager.getInstance(applicationContext)
            .createCancelPendingIntent(id)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            createChannel()
        }

        val notification = NotificationCompat.Builder(applicationContext, getChannelID())
            .setContentTitle(getTitle())
            .setTicker(getTitle())
            .setContentText(progress)
            .setSmallIcon(R.mipmap.me_data_icon)
            .setOngoing(true) //防止滑动删除
            .addAction(R.mipmap.me_data_icon, "取消", intent)
            .build()

        return ForegroundInfo("下载文件".hashCode(), notification)
    }
    @RequiresApi(Build.VERSION_CODES.O)
    private fun createChannel() {
        if (NotificationManagerCompat.from(applicationContext).getNotificationChannel(
                getChannelID()
            ) == null) {
            val name = "文件下载"
            val description = "文件下载"
            val importance = NotificationManager.IMPORTANCE_LOW
            val mChannel = NotificationChannel(getChannelID(), name, importance)
            mChannel.description = description
            mChannel.enableLights(true)
            mChannel.lightColor = Color.RED
            mChannel.enableVibration(true)
            return NotificationManagerCompat.from(applicationContext).createNotificationChannel(mChannel)
        }
    }

    private fun getTitle(): String {
        return "文件下载"
    }

    private fun getChannelID(): String {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            "文件下载"
        } else {
            ""
        }
    }

    companion object {
        const val KEY_INPUT_URL = "KEY_INPUT_URL"
        const val KEY_OUT_PUT_URL = "KEY_OUT_URL"
        const val KEY_OUTPUT_FILE_NAME = "KEY_OUTPUT_FILE_NAME"

        fun startDownload(context: Context, downloadUrl: String, outputFile: String, fileName: String): UUID {
            //1、封装数据，这里封装的是下载所需要的数据
            val inputData: Data = Data.Builder().apply {
                putString(KEY_INPUT_URL, downloadUrl)
                putString(KEY_OUTPUT_FILE_NAME, fileName)
                putString(KEY_OUT_PUT_URL, outputFile)
            }.build()
            //2、约束条件
            val constraints = Constraints.Builder()
                .setRequiredNetworkType(NetworkType.UNMETERED)
                .setRequiresStorageNotLow(true)
                .build()
            //3、创建一个一次性任务，DownloadWorker
            val request = OneTimeWorkRequestBuilder<DownloadWorker>()
                .setInputData(inputData)
                .setConstraints(constraints)
                .build()
            //4、执行WorkManager的request入队操作
            WorkManager.getInstance(context).enqueue(request)
            return request.id
        }
    }
}